#include <QWebFrame>
#include <QWebPage>
#include <QWebView>

#include "UIWebView.h"
#include "UIWindow.h"

class UIWebPage : public QWebPage {
    public:
        UIWebPage (QObject *parent = 0);
        ~UIWebPage();

        QString userAgent (void) const { return(m_userAgent); }
        void setUserAgent (const QString& agent) { m_userAgent = agent; }

    protected:
        QString userAgentForUrl (const QUrl& url) const { 
            Q_UNUSED(url);
            return(m_userAgent); 
        }

    private:
        QString m_userAgent;
};

UIWebPage::UIWebPage (QObject *parent)
    : QWebPage(parent)
{
    m_userAgent = "Mozilla/5.0 (iPhone; %Security%; CPU like Mac OS X; %Locale%) "
                  "AppleWebKit/%WebKitVersion% (KHTML, like Gecko) Safari/419.3)";
}

UIWebPage::~UIWebPage() {
}

class UIWebViewPrivate {
    public:
        QWebView *webView;
};

UIWebView::UIWebView (QGraphicsItem * parent)
    : QGraphicsProxyWidget(parent), UIResponder(window(), this), d(new UIWebViewPrivate)
{
    d->webView = new QWebView;
    setWidget(d->webView);

    // Setup WebPage
    UIWebPage *webPage = new UIWebPage(d->webView);
    d->webView->setPage(webPage);
}

UIWebView::~UIWebView() {
    d->webView->deleteLater();
    delete d;
}

void UIWebView::load (const QUrl& url) {
    d->webView->load(url);
}

void UIWebView::load (const QNetworkRequest& request,
                      QNetworkAccessManager::Operation operation,
                      const QByteArray& body)
{
    d->webView->load(request, operation, body);
}

void UIWebView::setContent (const QByteArray& data,
                            const QString& mimeType,
                            const QUrl& baseUrl)
{
    d->webView->setContent(data, mimeType, baseUrl);
}

void UIWebView::setHtml (const QString& html, const QUrl& baseUrl) {
    d->webView->setHtml(html, baseUrl);
}

qreal UIWebView::zoomFactor (void) const {
    return(d->webView->zoomFactor());
}

void UIWebView::setZoomFactor (qreal factor) {
    d->webView->setZoomFactor(factor);
}

UIWindow *UIWebView::window (void) const {
    return(static_cast<UIWindow *>(scene()));
}

QPointF UIWebView::scrollOffset (void) const {
	QWebFrame *frame = d->webView->page()->mainFrame();
    int x = frame->evaluateJavaScript("window.scrollX").toInt();
    int y = frame->evaluateJavaScript("window.scrollY").toInt();
	return(QPointF(x, y));
}

void UIWebView::setScrollOffset (const QPointF& pos) {
	QWebFrame *frame = d->webView->page()->mainFrame();
    QString js = "window.scrollTo(%1,%2);";
	frame->evaluateJavaScript(js.arg(pos.x()).arg(pos.y()));
}

void UIWebView::mouseReleaseEvent (QGraphicsSceneMouseEvent *event) {
    touchReleaseEvent(event);
}

void UIWebView::mousePressEvent (QGraphicsSceneMouseEvent *event) {
    touchPressEvent(event);
}

void UIWebView::mouseMoveEvent (QGraphicsSceneMouseEvent *event) {
    touchMoveEvent(event);
}

